/**
 *  根据文件组 groupId 来查询文件
 */
import { Request, Response } from "express";
import { putBucket } from "../plugins/oss/bucket";
import client from "../plugins/oss/client";

export default async (req: Request, res: Response) => {
  try {
    // 文件组ID
    const { groupId } = req.query;

    // 文件组限制不能为空
    if (!groupId) {
      res.send({
        code: 500,
        data: null,
        msg: "文件组ID不能为空",
      });
      return;
    }

    // 设置 OSS 的 bucket
    await putBucket();

    console.log("1111", Date.now());

    // 根据文件组的路径名称查询当前文件组下有哪些文件
    const result = await client.list(
      {
        prefix: `${groupId}/`, // 根据文件名或路径前缀过滤
        "max-keys": 1000, // 每次查询的最大文件数量
      },
      {}
    );
    console.log("2222", Date.now());

    // 查询的组内文件
    const objects: any = result.objects;

    // 批量查看组内文件的 meta 信息
    const promises = objects.map((file: any) => client.head(file.name));
    const resolves = await Promise.all(promises);
    console.log("3333", Date.now());

    // 组装信息返回
    result.objects = objects
      .map((i: any, index: number) => {
        return {
          url: i.url,
          name: resolves[index].meta.name,
          createdTime: i.lastModified,
          fileId: resolves[index].meta.fileid,
          groupId: resolves[index].meta.groupid,
          isUploadComplete:
            Number(resolves[index].meta.size) === Number(i.size),
        };
      })
      .filter((i: any) => i.isUploadComplete);

    res.send({
      code: 0,
      data: result.objects,
      // objects,
      // resolves,
      msg: "查询文件成功",
      // result,
    });
  } catch (err) {
    console.log(err);
    res.send({
      code: 500,
      data: null,
      msg: "查询文件异常",
    });
  }
};
